package cs575.fantasyclient.client;

import java.nio.ByteBuffer;
import java.util.List;

import cs575.common.FantasyMessage;
import cs575.common.OpCodes;
import cs575.common.Parser;
import cs575.common.Player;
import cs575.fantasyclient.services.GetAllPlayers;
import cs575.fantasyclient.services.GetPlayer;
import cs575.fantasyclient.ui.FantasyClient;

public class ClientParser extends Parser {

	@Override
	public FantasyMessage parseMessage(ByteBuffer bb) {
		FantasyMessage message = new FantasyMessage();
		byte opCode = bb.get();

		message.setOpCode(opCode);

		int messageSize = bb.getInt();

		if (messageSize > 0) {
			byte[] m = new byte[messageSize];
			bb.get(m);
			message.setMessage(m);
		} else {
			message.setMessage(new byte[0]);
		}

		FantasyMessage responseMsg = null;

		if (opCode == OpCodes.GET_ALL_PLAYERS_RESPONSE) {
			GetAllPlayers getAllService = new GetAllPlayers();
			List<Player> allPlayers = getAllService.execute(message);
			FantasyClient.addPlayers(allPlayers);
		} else if (opCode == OpCodes.REQUEST_PLAYER_RESPONSE){
			GetPlayer getPlayer = new GetPlayer();
			List<Player> player = getPlayer.execute(message);
			FantasyClient.updatePlayer(player);
		}

		return responseMsg;
	}

}
